from applications import create_app
import os
import ssl
from typing import Tuple
from logging.config import dictConfig
import logging
import shutil

# 配置日志
dictConfig({
    'version': 1,
    'formatters': {
        'default': {
            'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
        }
    },
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
            'formatter': 'default'
        },
        'file': {
            'class': 'logging.FileHandler',
            'filename': 'app.log',
            'formatter': 'default'
        }
    },
    'root': {
        'level': 'INFO',
        'handlers': ['console', 'file']
    }
})

# 配置常量
SSL_DIR = 'ssl'
SSL_CERT = os.path.join(SSL_DIR, 'cert.pemx')
SSL_KEY = os.path.join(SSL_DIR, 'privkey.pemx')
HOST = "0.0.0.0"
PORT = 21990
DEBUG = True
def ensure_ssl_directory() -> None:
    """确保SSL目录存在"""
    if not os.path.exists(SSL_DIR):
        os.makedirs(SSL_DIR)
        logging.info(f"Created SSL directory at {SSL_DIR}")

def verify_ssl_files() -> bool:
    """验证SSL证书文件是否有效"""
    try:
        if all([
            os.path.isfile(SSL_CERT),
            os.path.isfile(SSL_KEY),
            os.path.getsize(SSL_CERT) > 0,
            os.path.getsize(SSL_KEY) > 0
        ]):
            return True
        return False
    except OSError as e:
        logging.error(f"Error checking SSL files: {e}")
        return False

def get_ssl_context() -> Tuple[str, str]:
    """获取SSL上下文配置"""
    return (SSL_CERT, SSL_KEY)

def run_app(app) -> None:
    """运行应用程序"""
    try:
        if verify_ssl_files():
            logging.info("Starting app with SSL...")
            app.run(
                host=HOST,
                port=PORT,
                debug=DEBUG,
                ssl_context=get_ssl_context()
            )
        else:
            logging.warning("SSL files not found or invalid, starting without SSL...")
            app.run(
                host=HOST,
                port=PORT,
                debug=DEBUG
            )
    except ssl.SSLError as e:
        logging.error(f"SSL Error: {e}")
        logging.info("Falling back to non-SSL mode...")
        app.run(host=HOST, port=PORT, debug=DEBUG)
    except Exception as e:
        logging.error(f"Unexpected error: {e}")
        raise
def check_and_copy(): 
    db_path = "applications/db" 
    bak_path = "applications/dbbak" 
    files_to_check = ["iptv.db",  "jobs.sqlite"]  
 
    for file in files_to_check: 
        file_path = os.path.join(db_path,  file) 
        if not os.path.exists(file_path):  
            bak_file_path = os.path.join(bak_path,  file) 
            if os.path.exists(bak_file_path):  
                shutil.copy(bak_file_path,  file_path) 
 
def main():
    """主函数"""
    check_and_copy()
    ensure_ssl_directory()
    app = create_app()
    run_app(app)

if __name__ == '__main__':
    main()
	# app.run(host="0.0.0.0", port=21990, debug=False)
		
